#!/usr/bin/python
# Filename: macgenerator.py
# Description:
#   This a little program for keeping all the virtual servers
#   MAC address. It will automatically generate the MAC and
#   keep it into sqlite. 
# Author: Englebert Lai
# Date: 22 Jan 2011

import getopt
import os
import random
import sqlite3
import sys

def main():
  # Getting the parameters before proceeding
  from optparse import OptionParser
  usage = "usage: %prog [options] arg1 arg2"
  parser = OptionParser(usage=usage, version="%prog Version 1.0")
  
  parser.add_option("-H", "--hostname",
                    action="store", type="string", dest="hostname",
                    help="The hostname of the server for generating the MAC Address")
  parser.add_option("-d", "--device",
                    action="store", type="string", dest="device",
                    help="The network device name. e.g.: eth0")
  parser.add_option("-f", "--force",
                    action="store_true", default=False, dest="force",
                    help="Forcefully update if hostname and the device are the same")
  parser.add_option("-l", "--list",
                    action="store_false", default=True, dest="list",
                    help="List all the mac addresses")
  parser.add_option("-D", "--DELETE",
                    action="store_true", default=False, dest="delete_record",
                    help="Remove the record from the DB.")
  
  (options, args) = parser.parse_args()
  
  if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(2)

  if options.hostname == None and options.list == True:
    print "ERROR HOSTNAME!"
    parser.print_help()
    sys.exit(2)

  if options.device == None and options.list == True:
    print "ERROR DEVICE!"
    parser.print_help()
    sys.exit(2)

  macgenerator_db = "macgenerator.db"
  
  # Connection to the database
  db_connection = sqlite3.connect(macgenerator_db)
  
  # Create the cursor object to the db
  db_cursor = db_connection.cursor()
  
  # Making sure the table is exist else it will just create a new table
  try:
    db_cursor.execute('SELECT * FROM mackeeper;')
  except sqlite3.OperationalError, msg:
    print "Table not available! Creating new table."
    db_cursor.execute('''CREATE TABLE mackeeper ( 
    id INTEGER PRIMARY KEY,
    mac_address TEXT NOT NULL,
    server_name TEXT NOT NULL,
    device_name TEXT NOT NULL,
    created TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
    db_connection.commit()

  # Display all the records
  if options.list == False:
    db_cursor.execute('SELECT * FROM mackeeper ORDER BY server_name')
    results = db_cursor.fetchall()
    for line in results:
      print line[1] + ' - ' + line[2] + ' - ' + line[3]
    sys.exit(2)

  # Remove a single record
  # Make sure the record is exists else just exit
  if options.delete_record == True:
    db_cursor.execute('SELECT * FROM mackeeper WHERE server_name = "' + options.hostname + '" AND device_name = "' + options.device + '"')
    result = db_cursor.fetchone()
    if result != None:
      db_cursor.execute('DELETE FROM mackeeper WHERE server_name = "' + options.hostname + '" AND device_name = "' + options.device + '"')
      db_connection.commit()
      print "Removed."
    else:
      print "No record found."
    db_connection.close()
    sys.exit(0)

  # Starting the loop until is not matching
  exit_me = False

  while (exit_me == False):
    mac_address = GenerateMac()
    
    # Search from the DB if there is record then regenerate again
    db_cursor.execute('SELECT * FROM mackeeper WHERE mac_address = "' + mac_address + '"')
    results = db_cursor.fetchone()

    if results == None:
      # Insert to DB and proceed displaying the data
      # but also make sure no same host and same device else will just do an update.
      db_cursor.execute('SELECT * FROM mackeeper WHERE server_name = "' + options.hostname + '" AND device_name = "' + options.device + '"')
      results = db_cursor.fetchone()

      # Proceed if not the same else do an update
      if results == None:
        db_cursor.execute('INSERT INTO mackeeper (mac_address, server_name, device_name) VALUES ("' + mac_address + '", "' + options.hostname + '", "' + options.device + '")')
        db_connection.commit()
        print "Inserted DATA!"
      else:
        if options.force == True:
          db_cursor.execute('UPDATE mackeeper SET mac_address = "' + mac_address + '", server_name = "' + options.hostname + '", device_name = "' + options.device + '" WHERE server_name = "' + options.hostname + '" AND device_name = "' + options.device + '"')
          print "Updated DATA!"
        else:
          print "Same record in DB. Use -f or --force to update it."
          db_connection.close()
          sys.exit(2)

      # Display the data 
      print "HOSTNAME: " + options.hostname
      print "DEVICE: " + options.device
      print "MAC ADDRESS: " + mac_address
      
      db_connection.close()
      exit_me = True

def List_Me():
  return
# Generate a random MAC address
def GenerateMac():
  hexcode = '0123456789abcdef'
  i = 1
  mac = ''
  while (i <= 12):
    if i % 2 and i > 1:
      mac += ':'
    mac += random.choice(hexcode)
    i+=1
  return mac

def ListMe():
  return

if __name__ == "__main__":
  main()

